package com.eascs.workflow.wf.service.impl;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.workflow.common.entity.wf.DicData;
import com.eascs.workflow.common.entity.wf.ProcessNodeTemplate;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.wf.dao.ProcessNodeTemplateDao;
import com.eascs.workflow.wf.dao.ProcessTemplateDao;
import com.eascs.workflow.wf.service.TemplateService;

@Service
public class TemplateServiceImpl implements TemplateService {
	@Inject
	private ProcessTemplateDao processTemplateDao;
	@Inject
	private ProcessNodeTemplateDao processNodeTemplateDao;

	@Override
	public ProcessTemplate getProcessTemplate(String processNo) {
		return processTemplateDao.getById(ProcessTemplate.class, processNo);
	}

	@Override
	@Transactional("wfTransactionManager")
	public boolean copyTemplate(String processNo) {
		ProcessTemplate processTemplate = getProcessTemplate(processNo);
		List<ProcessNodeTemplate> nodeList = processNodeTemplateDao.getByProcessId(processNo);
		processTemplate.setProcessNo(null);
		processTemplate.setPublishStatus(ProcessTemplate.PUBLISH_STATUS_NO);
		processTemplate.setProcessName(processTemplate.getProcessName() + "[复制]");
		ProcessTemplate saveTemplate = processTemplateDao.insert(processTemplate);
		if (saveTemplate == null) {
			throw new RuntimeException("流程复制失败!");
		}
		for (ProcessNodeTemplate processNodeTemplate : nodeList) {
			processNodeTemplate.setNodeId(null);
			processNodeTemplate.setProcessNo(saveTemplate.getProcessNo());
			ProcessNodeTemplate nodeTmp = processTemplateDao.insert(processNodeTemplate);
			if (nodeTmp == null) {
				throw new RuntimeException("流程复制失败!");
			}
		}
		return true;
	}

	@Override
	@Transactional("wfTransactionManager")
	public boolean updateTemplateTimeEffective(String processNo) {
		int timeEffective = processNodeTemplateDao.findTemplateTimeEffective(processNo);
		processTemplateDao.updateTimeEffective(processNo, timeEffective);
		return true;
	}

	@Override
	public ModelResult<List<DicData>> getProcessTypeByCatagory(String catagory) {
		ModelResult<List<DicData>> modelResult = new ModelResult<List<DicData>>();
		List<DicData> list = processTemplateDao.getProcessTypeByCatagory(catagory);
		modelResult.withModel(list);
		return modelResult;
	}
}
